<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Db;
use app\common\controller\Api;

class Index extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    protected $layout = '';
    
    public function index()
    {
        echo '<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>首页-杭州吃喝不愁信息科技有限公司</title>
    <style>
        .container {
            width: 60%;
            margin: 10% auto 0;
            background-color: #f0f0f0;
            padding: 2% 5%;
            border-radius: 10px
        }

        ul {
            padding-left: 20px;
        }

            ul li {
                line-height: 2.3
            }

        a {
            color: #20a53a
        }
    </style>
</head>
<body>
    <div class="container" style="text-align:center;">
        <h1>网站正在建设中</h1>
        <h3>备案号：浙ICP备2023005554号</h3>
    </div>
</body>';
        // return $this->view->fetch();
    }


    /**
     * 30分钟提交单号超时，6小时提交凭证超时，每分钟执行一次
     * @DateTime 2023-05-01T11:56:14+0800
     * @return   [type]                   [description] 
     */
    public function orderTimeout()
    {
        $time = time();
        $OrderService = new \app\open\service\OrderService();
        Db::startTrans();
        try {
            // 30分钟提交单号超时
            $where = [
                // 'place_time'=>0,
                'wm_order_sn' => '',
                'order_status'=>1,
                'expire_time'=>['<=',$time]
            ];
            $order = Db::name('play_order')->field('id,expire_time,play_order_no,play_no,yunzhan_order_no,is_yunzhan,user_id,wm_order_sn,actual_rebate_amt,create_by')->where($where)->select();
            $Redis = new \think\cache\driver\Redis();
            if ($order) {
                // 更新订单状态
                Db::name('play_order')->where($where)->update(['order_status'=>-2,'cancel_reason'=>2,'update_by'=>'crontab1','update_dt'=>date('Y-m-d H:i:s',$time)]);
                $all = [];
                foreach ($order as $key => $value) {
                        $play_order_no = $value['play_order_no'];
                    $all[$key]['play_order_id'] = $value['id'];
                    $all[$key]['play_order_no'] = $play_order_no;
                    $all[$key]['info'] = '自动取消';
                    $all[$key]['create_by'] = 'crontab1';
                    // 名额   
                    $play_id = Db::name('play')->where(['play_no'=>$value['play_no']])->value('id');
                    Db::name('play')->where(['play_no'=>$value['play_no']])->setInc('chbcconsume');
                    if ($Redis->has('bdbplay'.$play_id)) {
                        $Redis->inc('bdbplay'.$play_id);
                    }
                    // 改变活动状态
                    // $complete_order = Db::name('play_order')->where(['play_no'=>$value['play_no'],'order_status'=>['in',[3,6,-9]]])->count();
                    // $play = \app\admin\model\Play::where(['play_no'=>$value['play_no']])->find();
                    // if (($complete_order==$play['chbcquota'] && $play['play_status']==2) || ($play['play_status']==4 && $complete_order==$play['chbcquota']-$play['chbcconsume'] && $play['chbcquota']-$play['chbcconsume']>0)) {
                    //         $play->play_status = 3;
                    //         $play->acture_total_money = (float)Db::name('play_order')->where(['play_no'=>$value['play_no'],'order_status'=>['in',[3,6,-9]]])->value('sum(actual_rebate_amt+service_charge_amt)');
                    //         $play->save();
                    // }
                    // 给渠道发通知
                    if ($value['create_by']=='api') {
                        $OrderService->statusChange($value['wm_order_sn'],$value['play_order_no'],-1,0,$value['actual_rebate_amt'],$value['is_yunzhan']);
                    }
                }
                // 日志
                Db::name('play_order_log')->insertAll($all);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            echo $e->getMessage();
        }
    }

    /**
     * 第二天13点取消前一天未提交凭证订单
     * @return [type] [description]
     */
    public function proofTimeout()
    {
        $time = time();
        $OrderService = new \app\open\service\OrderService();
        Db::startTrans();
        try {
            // 6小时提交凭证超时
            $where = [
                'wm_order_sn'=>['<>',''],
                'order_status'=>1,
                // 'expire_time'=>['<=',$time],
                'create_dt'=>['<=',date('Y-m-d',$time)]
            ];
            $order = Db::name('play_order')->field('id,expire_time,play_order_no,play_no,yunzhan_order_no,is_yunzhan,wm_order_sn,actual_rebate_amt,create_by')->where($where)->select();
            $Redis = new \think\cache\driver\Redis();
            if ($order) {
                // 订单状态
                Db::name('play_order')->where($where)->update(['order_status'=>-2,'cancel_reason'=>3,'update_by'=>'crontab3','update_dt'=>date('Y-m-d H:i:s',$time)]);
                $all = [];
                foreach ($order as $key => $value) {
                    $play_order_no = $value['play_order_no'];
                    $all[$key]['play_order_id'] = $value['id'];
                    $all[$key]['play_order_no'] = $play_order_no;
                    $all[$key]['info'] = '自动取消';
                    $all[$key]['create_by'] = 'crontab3';
                    // 名额
                    $play_id = Db::name('play')->where(['play_no'=>$value['play_no']])->value('id');
                    Db::name('play')->where(['play_no'=>$value['play_no']])->setInc('chbcconsume');
                    if ($Redis->has('bdbplay'.$play_id)) {
                        $Redis->inc('bdbplay'.$play_id);
                    }
                    // 改变活动状态
                    // $complete_order = Db::name('play_order')->where(['play_no'=>$value['play_no'],'order_status'=>['in',[3,6,-9]]])->count();
                    // $play = \app\admin\model\Play::where(['play_no'=>$value['play_no']])->find();
                    // if (($complete_order==$play['chbcquota'] && $play['play_status']==2) || ($play['play_status']==4 && $complete_order==$play['chbcquota']-$play['chbcconsume'] && $play['chbcquota']-$play['chbcconsume']>0)) {
                    //         $play->play_status = 3;
                    //         $play->acture_total_money = (float)Db::name('play_order')->where(['play_no'=>$value['play_no'],'order_status'=>['in',[3,6,-9]]])->value('sum(actual_rebate_amt+service_charge_amt)');
                    //         $play->save();
                    // }
                    // 给渠道发通知
                    if ($value['create_by']=='api') {
                        $OrderService->statusChange($value['wm_order_sn'],$value['play_order_no'],-1,0,$value['actual_rebate_amt'],$value['is_yunzhan']);
                    }   
                }
                // 日志
                Db::name('play_order_log')->insertAll($all);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            echo $e->getMessage();
        }
    }

    /**
     * 第二天12点取消前一天驳回状态订单
     * @DateTime 2023-06-07T14:47:54+0800
     * @param    string                   $value [description]
     */
    public function rejectOrderCancel()
    {
        $time = time();
        $OrderService = new \app\open\service\OrderService();
        Db::startTrans();
        try {
            // 驳回状态第二天取消
            $late6 = date('Y-m-d',$time);
            $where = [
                'order_status'=>-3,
                'create_dt'=>['<=',$late6]
            ];
            $order = Db::name('play_order')->field('id,expire_time,play_order_no,play_no,yunzhan_order_no,is_yunzhan,wm_order_sn,actual_rebate_amt,create_by')->where($where)->select();
            $Redis = new \think\cache\driver\Redis();
            if ($order) {
                // 订单状态
                Db::name('play_order')->where($where)->update(['order_status'=>-2,'cancel_reason'=>2,'update_by'=>'crontab4','update_dt'=>date('Y-m-d H:i:s',$time)]);
                $all = [];
                foreach ($order as $key => $value) {
                        $play_order_no = $value['play_order_no'];
                    $all[$key]['play_order_id'] = $value['id'];
                    $all[$key]['play_order_no'] = $play_order_no;
                    $all[$key]['info'] = '自动取消';
                    $all[$key]['create_by'] = 'crontab4';
                    // 名额
                    $play_id = Db::name('play')->where(['play_no'=>$value['play_no']])->value('id');
                    Db::name('play')->where(['play_no'=>$value['play_no']])->setInc('chbcconsume');
                    if ($Redis->has('bdbplay'.$play_id)) {
                        $Redis->inc('bdbplay'.$play_id);
                    }
                    // 改变活动状态
                    // $complete_order = Db::name('play_order')->where(['play_no'=>$value['play_no'],'order_status'=>['in',[3,6,-9]]])->count();
                    // $play = \app\admin\model\Play::where(['play_no'=>$value['play_no']])->find();
                    // if (($complete_order==$play['chbcquota'] && $play['play_status']==2) || ($play['play_status']==4 && $complete_order==$play['chbcquota']-$play['chbcconsume'] && $play['chbcquota']-$play['chbcconsume']>0)) {
                    //         $play->play_status = 3;
                    //         $play->acture_total_money = (float)Db::name('play_order')->where(['play_no'=>$value['play_no'],'order_status'=>['in',[3,6,-9]]])->value('sum(actual_rebate_amt+service_charge_amt)');
                    //         $play->save();
                    // }
                    // 给渠道发通知
                    if ($value['create_by']=='api') {
                        $OrderService->statusChange($value['wm_order_sn'],$value['play_order_no'],-1,0,$value['actual_rebate_amt'],$value['is_yunzhan']);
                    }
                }
                // 日志
                Db::name('play_order_log')->insertAll($all);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            echo $e->getMessage();
        }
    }

    /**
     * 循环活动生成子活动，凌晨两点执行
     * @DateTime 2023-05-01T12:30:54+0800
     * @return   [type]                   [description]
     */
    public function createPlays()
    {
        $time = time();
        $today_start = strtotime(date('Ymd',$time));
        $today_end = strtotime(date('Ymd',$time))+86399;
        $create_dt = date('Y-m-d H:i:s',$time);
        $plays = Db::name('play')->where(['super_play_no'=>['>',0],'play_status'=>2,'start_date'=>['<=',$today_start],'end_date'=>['>=',$today_end]])->field('*')->select();
        Db::startTrans();
        try {
            $all = [];
            if ($plays) {
                foreach ($plays as $key => $value) {
                    // 是否已经生成
                    if (Db::name('play')->where(['parent_play_no'=>$value['super_play_no'],'start_date'=>$today_start,'end_date'=>$today_end])->count()) {
                        continue;
                    }
                    $shop = (new \app\admin\model\Shop())->where(['shop_no' => $value['shop_no'], 'shop_status' => 1])->find();
                    if (empty($shop)) continue;
                    $play_no = $this->generateNo(['biz_tag'=>'play_no','len'=>12,'int_prefix'=>2]);
                    $all[$key]['play_no'] = $play_no;
                    $all[$key]['user_id'] = $value['user_id'];
                    $all[$key]['shop_no'] = $value['shop_no'];
                    $all[$key]['shop_name'] = $shop['shop_name'];
                    $all[$key]['play_type'] = $value['play_type'];
                    $all[$key]['start_date'] = $today_start;
                    $all[$key]['end_date'] = $today_end;
                    $all[$key]['start_time_str'] = $value['start_time_str'];
                    $all[$key]['end_time_str'] = $value['end_time_str'];
                    $all[$key]['scheme_no'] = $value['scheme_no'];
                    $all[$key]['service_amt'] = $value['service_amt'];
                    $all[$key]['service_admin_id'] = $shop['salesman_admin_id'];
                    $all[$key]['service_admin_by'] = strval(\app\admin\model\Admin::where('id',$shop['salesman_admin_id'])->value('nickname'));
                    $all[$key]['deal_content'] = $value['deal_content'];
                    $all[$key]['play_status'] = 2;
                    $all[$key]['pay_status'] = $value['pay_status'];
                    $all[$key]['last_pay_time'] = 0;
                    $all[$key]['acture_pay'] = 0;
                    $all[$key]['order_over_num'] = 0;
                    $all[$key]['submit_uid'] = $value['submit_uid'];
                    $all[$key]['submit_admin_id'] = $value['submit_admin_id'];
                    $all[$key]['create_by'] = $value['create_by'];
                    $all[$key]['update_by'] = $value['update_by'];
                    $all[$key]['user_pay'] = $value['user_pay'];
                    $all[$key]['shop_settlement'] = $value['shop_settlement'];
                    $all[$key]['num'] = $value['num'];
                    $all[$key]['machine_audit'] = $value['machine_audit'];
                    $all[$key]['remarks'] = $value['remarks'];
                    $all[$key]['img'] = $shop['logo_pic'];
                    $all[$key]['total_pay'] = $value['total_pay'];
                    $all[$key]['total_service_amt'] = $value['total_service_amt'];
                    $all[$key]['total_money'] = $value['total_money'];
                    $all[$key]['acture_total_money'] = $value['total_money'];
                    $all[$key]['is_pay'] = $value['is_pay'];
                    $all[$key]['back_money'] = $value['back_money'];
                    $all[$key]['play_label'] = $value['play_label'];
                    $all[$key]['shop_type'] = $shop['shop_type'];
                    $all[$key]['stock'] = $value['num'];
                    $all[$key]['pay_type'] = $value['pay_type'];
                    $all[$key]['approve_by'] = $value['approve_by'];
                    $all[$key]['approve_time'] = $value['approve_time'];
                    $all[$key]['times_limit'] = $value['times_limit'];
                    $all[$key]['jt'] = $value['jt'];
                    $all[$key]['jc'] = $value['jc'];
                    $all[$key]['reject_content'] = $value['reject_content'];
                    $all[$key]['parent_play_no'] = $value['super_play_no'];
                    $all[$key]['is_qcsc'] = $value['is_qcsc'];
                    $all[$key]['channel'] = $value['channel'];
                    $all[$key]['virtual_num'] = 0;
                    if ($all[$key]['play_label']>0) {
                        $all[$key]['virtual_num'] = mt_rand(0,5);
                    }
                    $all[$key]['create_dt'] = $create_dt;
                    $all[$key]['chbcquota'] = $value['chbcquota'];
                    $all[$key]['chbcconsume'] = $value['chbcquota'];
                    $all[$key]['middleman_id'] = $shop['middleman_id'];
                }
            }
            Db::name('play')->insertAll($all);
            $newplay = Db::name('play')->where(['parent_play_no'=>['>',0],'create_dt'=>$create_dt])->field('id,channel,chbcconsume')->select();
            $channels = [];
            $Redis = new \think\cache\driver\Redis();
            foreach ($newplay as $k2 => $v2) {
                $channel = json_decode($v2['channel'],1);
                foreach ($channel as $k => &$v) {
                    $v['play_id'] = $v2['id'];
                    if ($v['channel_status']=='未分发') {
                        $v['status'] = 0;
                    } elseif ($v['channel_status']=='已分发') {
                        $v['status'] = 1;
                    } elseif ($v['channel_status']=='无法分发已处理') {
                        $v['status'] = 2;
                    } elseif ($v['channel_status']=='无法分发') {
                        $v['status'] = 3;
                    } elseif ($v['channel_status']=='已结束') {
                        $v['status'] = 4;
                    } else {
                        $v['status'] = 0;
                    }
                    unset($v['channel_name']);
                    unset($v['channel_status']);
                    $v['is_son'] = 1;
                    $channels[] = $v;
                }
                $Redis->set('bdbplay'.$v2['id'],$v2['chbcconsume'],86400); // 缓存库存
            }
            Db::name('play_channel')->insertAll($channels);
            // 上一日的活动手续费固定下来
            $end = date('Y-m-d');
            $start = date('Y-m-d',strtotime($end)-86400);
            $shop = Db::name('play')->where('create_dt>"'.$start.'" and create_dt<="'.$end.'"')->group('shop_no')->field('shop_no')->select();
            foreach ($shop as $key => $value) {
                $shop_serviceamt = Db::name('shop_serviceamt')->where('shop_no',$value['shop_no'])->select();
                if (!$shop_serviceamt) continue;
                $update = [];
                foreach ($shop_serviceamt as $s) {
                    $update[$s['channel_id']] = $s['service_amt'];
                }
                Db::name('play')->where('shop_no='.$value['shop_no'].' and create_dt>"'.$start.'" and create_dt<="'.$end.'"')->update(['channel_service_amt'=>json_encode($update)]);
            }
            Db::commit();
        } catch (\Exception $e) {
            echo $e->getMessage();
            Db::rollback();
        }
    }


    /**
     * 每日抽奖次数重置，凌晨0点执行
     * @DateTime 2023-05-01T14:47:18+0800
     * @return   [type]                   [description]
     */
    public function luckdrawTimes()
    {
        $users = Db::name('user')->where(['luckdraw_num'=>['>',0]])->field('id')->count();
        if ($users) {
            Db::name('user')->where(['luckdraw_num'=>['>',0]])->update(['luckdraw_num'=>0,'updatetime'=>time()]);
        }
    }


    /**
     * vip用户每月赠送优惠券，每月第一天凌晨5点执行
     * @DateTime 2023-05-01T14:51:17+0800
     * @return   [type]                   [description]
     */
    public function vipRollBak()
    {
        $time = time();
        $membership_benefits = [];
        $membership_benefits[1] = Db::name('config')->field('name,value')->where(['name'=>'membership_benefits1'])->find();
        $membership_benefits[2] = Db::name('config')->field('name,value')->where(['name'=>'membership_benefits2'])->find();
        $membership_benefits[3] = Db::name('config')->field('name,value')->where(['name'=>'membership_benefits3'])->find();
        $membership_benefits[4] = Db::name('config')->field('name,value')->where(['name'=>'membership_benefits4'])->find();
        $membership_benefits[5] = Db::name('config')->field('name,value')->where(['name'=>'membership_benefits5'])->find();
        $users = Db::name('user')->field('id,level')->where(['status'=>'normal','is_limited'=>0,'level'=>['>',0]])->select();
        $cards = [];
        $cards['card_one']=Db::name('config')->where('name','card_one')->value('value');
        $cards['card_two']=Db::name('config')->where('name','card_two')->value('value');
        $cards['card_three']=Db::name('config')->where('name','card_three')->value('value');
        $cards['card_four']=Db::name('config')->where('name','card_four')->value('value');
        $cards['card_five']=Db::name('config')->where('name','card_five')->value('value');
        Db::startTrans();
        $data = [];
        try {
            foreach ($users as $u) {
                // 过去30天是否已经赠送
                $where = [];
                $where['source'] = 'VIP每月赠送';
                $where['user_id'] = $u['id'];
                $where['level'] = $u['level'];
                $where['expire_time'] = ['>=',$time+600];// 有时候凌晨执行会出现几秒的提前，导致应该发券的没发，所以-600
                $roll = Db::name('user_roll')->where($where)->find();
                if (!$roll) {
                    // $level = substr($membership_benefits[$u['level']]['name'],-1);
                    $card = json_decode($membership_benefits[$u['level']]['value'],1);
                    if ($u && $card) {
                        foreach ($card as $k1 => $v1) {
                            for ($i=0; $i < $v1; $i++) { 
                                $all = [];
                                $all['roll_type'] = $k1;
                                $all['roll_name'] = $cards[$k1];
                                $all['user_id'] = $u['id'];
                                $all['expire_time'] = $time+2592000;
                                $all['source'] = 'VIP每月赠送';
                                $all['level'] = $u['level'];
                                $data[] = $all; 
                            }
                        }
                    }
                }
            }
            Db::name('user_roll')->insertAll($data);
            Db::commit();
        } catch (\Exception $e) {
            echo $e->getMessage();
            Db::rollback();
        }
    }


    /**
     * vip用户每月赠送优惠券，每月第一天凌晨5点执行
     * @DateTime 2023-05-01T14:51:17+0800
     * @return   [type]                   [description]
     */
    public function vipRoll()
    {
        $id=30000;
        $time = time();
        $config = Db::name('config')->field('name,value')->where(['name'=>['like','membership_benefits%']])->select();
        $expire_time = strtotime('+1 month');
        Db::startTrans();
        try {
            $data = [];
            foreach ($config as $key => $value) {
                // 过去30天是否已经赠送
                $where = [];
                $where['source'] = 'VIP每月赠送';
                $where['create_dt'] = ['>=',date('Y-m-d',$time)];
                $where['user_id'] = ['<',$id];

                $roll = Db::name('user_roll')->where($where)->find();
                if ($roll) continue;
                
                $level = substr($value['name'],-1);
                $card = json_decode($value['value'],1);
                $where="id<".$id." and status='normal' and is_limited=0 and level=".$level;
                $users = Db::name('user')->field('id')->where($where)->select();
                if ($users && $card) {
                    foreach ($users as $k => $v) {
                        foreach ($card as $k1 => $v1) {
                            for ($i=0; $i < $v1; $i++) { 
                                $all = [];
                                $all['roll_type'] = $k1;
                                $all['roll_name'] = Db::name('config')->where('name',$k1)->value('value');
                                $all['user_id'] = $v['id'];
                                $all['expire_time'] = $expire_time;
                                // $all['expire_time'] = $time+30*86400;
                                $all['source'] = 'VIP每月赠送';
                                $data[] = $all; 
                            }
                        }
                    }
                }
            }
            Db::name('user_roll')->insertAll($data);
            Db::commit();
        } catch (\Exception $e) {
            echo $e->getMessage();
            Db::rollback();
        }
    }


    /**
     * vip用户每月赠送优惠券，每月第一天凌晨5点执行
     * @DateTime 2023-05-01T14:51:17+0800
     * @return   [type]                   [description]
     */
    public function vipRoll3()
    {
        $id=30000;
        $id2=60000;
        $time = time();
        $config = Db::name('config')->field('name,value')->where(['name'=>['like','membership_benefits%']])->select();
        $expire_time = strtotime('+1 month');
        Db::startTrans();
        try {
            $data = [];
            foreach ($config as $key => $value) {
                // 过去30天是否已经赠送
                $where = [];
                $where['source'] = 'VIP每月赠送';
                $where['create_dt'] = ['>=',date('Y-m-d',$time)];
                $where['user_id'] = ['>=',$id];
                $where['user_id'] = ['<',$id2];

                $roll = Db::name('user_roll')->where('source="VIP每月赠送" and create_dt>="'.date('Y-m-d',$time).'" and user_id<'.$id2.' and user_id>='.$id)->find();
                if ($roll) continue;
                
                $level = substr($value['name'],-1);
                $card = json_decode($value['value'],1);
                $where="id<".$id2." and id>=".$id." and status='normal' and is_limited=0 and level=".$level;
                $users = Db::name('user')->field('id')->where($where)->select();
                if ($users && $card) {
                    foreach ($users as $k => $v) {
                        foreach ($card as $k1 => $v1) {
                            for ($i=0; $i < $v1; $i++) { 
                                $all = [];
                                $all['roll_type'] = $k1;
                                $all['roll_name'] = Db::name('config')->where('name',$k1)->value('value');
                                $all['user_id'] = $v['id'];
                                $all['expire_time'] = $expire_time;
                                // $all['expire_time'] = $time+30*86400;
                                $all['source'] = 'VIP每月赠送';
                                $data[] = $all; 
                            }
                        }
                    }
                }
            }
            Db::name('user_roll')->insertAll($data);
            Db::commit();
        } catch (\Exception $e) {
            echo $e->getMessage();
            Db::rollback();
        }
    }


    /**
     * vip用户每月赠送优惠券，每月第一天凌晨5点执行
     * @DateTime 2023-05-01T14:51:17+0800
     * @return   [type]                   [description]
     */
    public function vipRoll2()
    {
        $id = 60000;
        $time = time();
        $config = Db::name('config')->field('name,value')->where(['name'=>['like','membership_benefits%']])->select();
        $expire_time = strtotime('+1 month');
        Db::startTrans();
        try {
            $data = [];
            foreach ($config as $key => $value) {
                // 过去30天是否已经赠送
                $where = [];
                $where['source'] = 'VIP每月赠送';
                $where['create_dt'] = ['>=',date('Y-m-d',$time)];
                $where['user_id'] = ['>=',$id];
                $roll = Db::name('user_roll')->where($where)->find();
                if ($roll) continue;
                
                $level = substr($value['name'],-1);
                $card = json_decode($value['value'],1);
                $where="id>=".$id." and status='normal' and is_limited=0 and level=".$level;
                $users = Db::name('user')->field('id')->where($where)->select();
                if ($users && $card) {
                    foreach ($users as $k => $v) {
                        foreach ($card as $k1 => $v1) {
                            for ($i=0; $i < $v1; $i++) { 
                                $all = [];
                                $all['roll_type'] = $k1;
                                $all['roll_name'] = Db::name('config')->where('name',$k1)->value('value');
                                $all['user_id'] = $v['id'];
                                $all['expire_time'] = $expire_time;
                                // $all['expire_time'] = $time+30*86400;
                                $all['source'] = 'VIP每月赠送';
                                $data[] = $all; 
                            }
                        }
                    }
                }
            }
            Db::name('user_roll')->insertAll($data);
            Db::commit();
        } catch (\Exception $e) {
            echo $e->getMessage();
            Db::rollback();
        }
    }


    /**
     * 优惠券失效
     * @DateTime 2023-05-01T15:18:05+0800
     * @return   [type]                   [description]
     */
    public function rollExpire()
    {
        $time = time();
        $roll = Db::name('user_roll')->where(['expire_time'=>['<',$time],'status'=>1])->count();
        if ($roll) {
            Db::name('user_roll')->where(['expire_time'=>['<',$time],'status'=>1])->update([
                'status'=>3,
                'update_dt'=>date('Y-m-d H:i:s',$time)
            ]);
        }
    }

    /**
     * 已结束活动,5分钟执行一次
     * @DateTime 2023-05-01T15:23:16+0800
     * @return   [type]                   [description]
     */
    public function endPlay()
    {
        $time = time();
        $today_start = strtotime(date('Ymd',$time));
        $today_end = strtotime(date('Ymd',$time))+86399;
        $plays = Db::name('play')->field('*')->where(['play_status'=>['in','0,1,2']])->select();
        Db::startTrans();
        try {
            foreach ($plays as $key => $value) {
                $start_time = strtotime(date('Ymd',$value['end_date']).' '.$value['start_time_str']);
                $end_time = strtotime(date('Ymd',$value['end_date']).' '.$value['end_time_str']);
                if ($value['super_play_no']==0) { // 普通活动
                    if ($time>$end_time) {
                        $update = ['play_status'=>4,'update_by'=>'crontab5','update_dt'=>date('Y-m-d H:i:s',$time)];
                        $update['acture_total_money'] = (float)\app\common\model\Order::where(['play_no'=>$value['play_no'],'order_status'=>['in',[3,6,-9]]])->value('sum(actual_rebate_amt+service_charge_amt)');
                        if (\app\common\model\Order::where(['play_no'=>$value['play_no'],'order_status'=>['in',[3,6,-9]]])->count()==$value['num']-$value['stock'] && $value['num']-$value['stock']>0) {
                            // 如果是前台发布的活动，此时直接完成活动,否则状态改为待支付
                            if ($value['pay_status']==3 && $value['is_pay']==1) {
                                $update['play_status'] = 5;
                                $update['pay_status'] = 2;
                                $update['last_pay_time'] = time();
                                // 冻结金额减少
                                $money = -1*($value['total_money']-$update['acture_total_money']);
                                (new \app\common\model\User())->money($money, $value['user_id'], '商家结算', $value['play_no'], 1);
                                // 商家余额增加
                                $money = -1*$money;
                                (new \app\common\model\User())->money($money, $value['user_id'], '商家结算', $value['play_no']);
                                // 订单支付状态
                                \app\common\model\Order::where(['play_no'=>$value['play_no'],'order_status'=>['in',[3,6,-9]]])->update(['is_pay'=>1,'pay_time'=>$time]);

                            } else {
                                $update['play_status'] = 3;
                            }
                        } else {
                            $update['play_status'] = 4;
                            // 前台发布活动没消耗的名额退还冻结金额
                            // if ($value['pay_status']==3 && $value['is_pay']==1) {
                            //     // 冻结金额减少
                            //     $money = -1*($value['total_money']-$update['acture_total_money']);
                            //     (new \app\common\model\User())->money($money, $value['user_id'], '商家结算', $value['play_no'], 1);
                            //     // 商家余额增加
                            //     $money = -1*$money;
                            //     (new \app\common\model\User())->money($money, $value['user_id'], '商家结算', $value['play_no']);
                            // }
                        }
                        Db::name('play')->where(['id'=>$value['id']])->update($update);
                        // 修改渠道活动状态为已结束
                        if (Db::name('play_channel')->where(['play_id'=>$value['id']])->find()) {
                            Db::name('play_channel')->where(['play_id'=>$value['id']])->update([
                                'activity_status' => 2,
                                'update_dt' => date('Y-m-d H:i:s'),
                                'operate_status' => 1,
                                'status' => 4
                            ]);
                        }


                    }
                } else { // 循环活动
                    if ($value['end_date']<$time) {
                        Db::name('play')->where(['id'=>$value['id']])->update(['pay_status'=>2,'play_status'=>4,'update_by'=>'crontab5','update_dt'=>date('Y-m-d H:i:s',$time)]);
                        // 修改渠道活动状态为已结束
                        if (Db::name('play_channel')->where(['play_id'=>$value['id']])->find()) {
                            Db::name('play_channel')->where(['play_id'=>$value['id']])->update([
                                'activity_status' => 2,
                                'update_dt' => date('Y-m-d H:i:s'),
                                'operate_status' => 1,
                                'status' => 4
                            ]);
                        }
                    }
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            echo $e->getMessage();exit;
        }
        echo 'succ';exit;
    }

    // 3分钟执行一次
    public function cpsList()
    {
        $time = time();
        $requestId = rand(1000,9999).$time;
        Db::startTrans();
        try {
            // $cps = Db::name('cps')->where(['type'=>3])->order('id DESC')->find();
            // if (isset($cps['createtime']) && $cps['createtime']) {
            //     $start_date = date('Y-m-d H:i:s',$cps['createtime']);
            //     $end_date = date('Y-m-d H:i:s',$time);
            //     $page = 1;
            // } else {
                // 9小时
                $start_date = date('Y-m-d H:i:s',$time-3600);
                $end_date = date('Y-m-d H:i:s',$time);
                $page = 1;
            // }
            $res = $this->elemInsert($start_date,$end_date,$page,$time,'cps');
            if (!$res) {
                Db::rollback();
                return false;
            }
            // $cps = Db::name('cps')->where(['type'=>4])->order('id DESC')->find();
            // if (isset($cps['createtime']) && $cps['createtime']) {
            //     $start_date = date('Y-m-d H:i:s',$cps['createtime']);
            //     $end_date = date('Y-m-d H:i:s',$time);
            //     $page = 1;
            // } else {
            //     $start_date = date('Y-m-d H:i:s',$time-2592000);
            //     $end_date = date('Y-m-d H:i:s',$time);
            //     $page = 1;
            // }
            // $res = $this->elemInsert($start_date,$end_date,$page,$time,'cpa');
            // if (!$res) {
            //     Db::rollback();
            //     return false;
            // }
            
            // $cps = Db::name('cps')->where(['type'=>1])->order('id DESC')->find();
            // if (isset($cps['createtime']) && $cps['createtime']) {
            //     $start_date = date('Y-m-d H:i:s',$cps['createtime']);
            //     $end_date = date('Y-m-d H:i:s',$time);
            //     $page = 1;
            // } else {
                // 9小时
                $start_date = $time-3600;
                $end_date = $time;
                $page = 1;
            // }
            $res = $this->meituanInsert($start_date,$end_date,$page,'',$time,'cps');
            if (!$res) {
                Db::rollback();
                return false;
            }
            // $cps = Db::name('cps')->where(['type'=>2])->order('id DESC')->find();
            // if (isset($cps['createtime']) && $cps['createtime']) {
            //     $start_date = date('Y-m-d H:i:s',$cps['createtime']);
            //     $end_date = date('Y-m-d H:i:s',$time);
            //     $page = 1;
            // } else {
            //     $start_date = date('Y-m-d H:i:s',$time-2592000);
            //     $end_date = date('Y-m-d H:i:s',$time);
            //     $page = 1;
            // }
            // $res = $this->meituanInsert($start_date,$end_date,$page,$requestId,$time,'cpa');
            // if (!$res) {
            //     Db::rollback();
            //     return false;
            // }
            // 判断有没有cps订单
            $where = [
                'handle_status' => 0,
                'one_image' => ['=',''],
                'create_dt' => ['>',date('Y-m-d H:i:s',$time-259200)]
            ];
            $proof = Db::name('play_order_proof')->where($where)->field('id,play_order_no,wm_order_sn,user_pay')->select();
            foreach ($proof as $key => $value) {
                // $cps = Db::name('cps')->where(['order_id'=>$value['wm_order_sn']])->find();
                $cps = Db::name('cps')->where(['createtime'=>['>',$time-86400],'order_id'=>$value['wm_order_sn']])->find();
                // 匹配上了后比对实付金额和店铺信息
                if ($cps) {
                    // cps状态是否符合
                    if ((in_array($cps['type'], [1,2]) && in_array($cps['status'], [2,3])) || (in_array($cps['type'], [3,4]) && in_array($cps['status'], [4]))) {
                        $order = Db::name('play_order')->field('id,shop_name')->where('play_order_no',$value['play_order_no'])->find();
                        if (!$order) {
                            $order = Db::name('play_order')->field('id,shop_name')->where('yunzhan_order_no',$value['play_order_no'])->find();
                        }
                        $order['shop_name'] = str_replace('（', '(', $order['shop_name']);
                        $order['shop_name'] = str_replace('）', ')', $order['shop_name']);
                        $order['shop_name'] = str_replace(' ', '', $order['shop_name']);
                        $cps['shop_name'] = str_replace('（', '(', $cps['shop_name']);
                        $cps['shop_name'] = str_replace('）', ')', $cps['shop_name']);
                        $cps['shop_name'] = str_replace(' ', '', $cps['shop_name']);
                        if ($order['shop_name']==$cps['shop_name'] && $cps['amount']>$value['user_pay']) {
                            Db::name('play_order')->where('id',$order['id'])->update([
                                'cps_id'=>$cps['id'],
                                'update_dt'=>date('Y-m-d H:i:s',$time),
                                'update_by'=>'crontab6',
                            ]);
                        }
                    }
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            \think\Log::write('拉取cps订单：'.$e->getMessage());
            return false;
        }
        $this->success('');
    }


    public function meituanInsert($start_date,$end_date,$page,$requestId,$time,$cps)
    {
        $appkey=config('meituan.appkey');
        $appsecret=config('meituan.appsecret');
        $mtid=config('meituan.mtid');
        $sid=config('meituan.sid');
        $Obj = new \services\MeituanService($appkey,$appsecret);
        $param = [
          'limit' => 50,
          'queryTimeType' => 1, //1 按订单支付时间查询， 2 按照更新时间查询， 默认为1
          'startTime' => $start_date,
          'endTime' => $end_date,
          'sid' => $sid,
          'searchType' => 2, //订单分页查询方案选择，不填则默认为1。1 分页查询（最多能查询到1万条订单），当选择本查询方案，page参数不能为空。此查询方式后续不再维护，建议使用2逐页查询。2 逐页查询（不限制查询订单数，只能逐页查询，不能指定页数），当选择本查询方案，需配合scrollId参数使用
          'scrollId' => $requestId,
        ];
        Db::startTrans();
        try {
            if ($cps=='cps') {
                $param['tradeType'] = 1;//1表示CPS，2表示CPA
                $res = $Obj->getCpsOrderList($param,$requestId);
            } else {
                $param['tradeType'] = 2;
                $res = $Obj->getCpaOrderList($param,$requestId);
            }
            // \think\log::write('美团cpsdata:'.$res);
            $res = json_decode($res,1);
            $data = [];
            if (isset($res['code']) && $res['code']==0) {
                foreach ($res['data']['dataList'] as $key => $value) {
                    // if (!Db::name('cps')->where(['order_id'=>$value['orderId']])->count() && $value['itemBizStatus']==2) {
                    if (!Db::name('cps')->where(['order_id'=>$value['orderId']])->count()) {
                        $all = [];
                        $all['order_id'] = $value['orderId'];
                        $all['amount'] = $value['payPrice'];
                        //status-2：付款（如果是CPA订单则表示奖励已创建） 3：完成 4：取消 5：风控 6：结算
                        if ($value['status']==2) {
                            $all['status'] = 1;
                        } elseif ($value['status']==3) {
                            $all['status'] = 2;
                        } elseif ($value['status']==6) {
                            $all['status'] = 3;
                        } else {
                            $all['status'] = $value['status'];
                        }
                        $all['shop_name'] = $value['productName'];
                        $all['pay_time'] = date('Y-m-d H:i:s',$value['payTime']);
                        if ($cps=='cps') {
                            $all['type'] = 1;//1-美团cps2-美团cpa3-饿了么cps4-饿了么cpa
                        } else {
                            $all['type'] = 2;//1-美团cps2-美团cpa3-饿了么cps4-饿了么cpa
                        }
                        $all['createtime'] = $time;
                        $all['content'] = json_encode($value);
                        $data[] = $all;
                    }
                }
            }
            Db::name('cps')->insertAll($data);
            if ($param['limit']<=count($res['data']['dataList'])) {
                $res2 = $this->meituanInsert($start_date,$end_date,$page+1,$res['data']['scrollId'],$time,$cps);
                if (!$res2) {
                    Db::rollback();
                    return false;
                }
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }


    public function elemInsert($start_date,$end_date,$page,$time,$cps)
    {
        $Obj = new \services\ElemService();
        $param = [
          'biz_unit'=>2, //1-CPA 2-CPS
          'page_size'=>50,
          'page_number'=>$page,
          'start_date' => $start_date,
          'end_date' => $end_date,
          'date_type' => 1, //时间维度，1-付款时间 2-创建时间 3-结算时间 4-更新时间
        ];
        if ($cps=='cpa') {
            $param['biz_unit'] = 1;
        }
        Db::startTrans();
        try {
            $res = $Obj->getOrderList($param);
            var_dump($res);exit;
            // \think\log::write('饿了么cpsdata:'.$res);
            $res = json_decode($res,1);
            $data = [];
            if (isset($res['alibaba_alsc_union_kbcpx_positive_order_get_response']['result']['order_detail_report_d_t_o']) && $res['alibaba_alsc_union_kbcpx_positive_order_get_response']['result']['order_detail_report_d_t_o']) {
                foreach ($res['alibaba_alsc_union_kbcpx_positive_order_get_response']['result']['order_detail_report_d_t_o'] as $key => $value) {
                    if (!Db::name('cps')->where(['order_id'=>$value['biz_order_id']])->count() && $value['order_state']==4) {
                        $all = [];
                        $all['order_id'] = $value['biz_order_id'];
                        $all['amount'] = $value['pay_amount'];
                        $all['status'] = $value['order_state'];//0已失效，1已下单，2已付款，3售中退，4已收货，5售后退
                        $all['shop_name'] = $value['shop_name'];
                        $all['pay_time'] = $value['pay_time'];
                        if ($cps=='cps') {
                            $all['type'] = 3;//1-美团cps2-美团cpa3-饿了么cps4-饿了么cpa
                        } else {
                            $all['type'] = 4;//1-美团cps2-美团cpa3-饿了么cps4-饿了么cpa
                        }
                        $all['createtime'] = $time;
                        $all['content'] = json_encode($value);
                        $data[] = $all;
                    }
                }
            }
            Db::name('cps')->insertAll($data);
            if ($res['alibaba_alsc_union_kbcpx_positive_order_get_response']['total_count']>$page*20) {
                $res2 = $this->elemInsert($start_date,$end_date,$page+1,$time,$cps);
                if (!$res2) {
                    Db::rollback();
                    return false;
                }
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }

    /**
     * 图片信息识别
     * @DateTime 2023-05-15T22:08:55+0800
     * @param    [type]                   $shop_type [description]
     * @param    array                    $proof     [description]
     * @return   [type]                              [description]
     */
    public function ocr()
    {
        $play_order_no = input('play_order_no','');
        $order = \app\common\model\Order::where(['play_order_no'=>$play_order_no])->find();
        $proof = \app\common\model\OrderProof::where('play_order_no',$play_order_no)->order('id desc')->field('*')->find();
        $play = (new \app\admin\model\Play())->where('play_no', $order['play_no'])->find();
        $OcrService = new \app\api\service\OcrService();
        $res = $OcrService->ocr1($play, $order, $proof ,$proof);
        var_dump($res);exit;
    }


    /**
     * 处理三天前的活动，有些活动因为各种原因没有变成待支付状态，这里改变活动状态
     * @return [type] [description]
     */
    public function handlePlay()
    {
        Db::startTrans();
        try {
            $time = time();
            $date = date('Y-m-d');
            $threeday_before = strtotime($date)-3*86400;

            $order = Db::name('play_order')->alias('po')->join('chbc_play p','p.play_no=po.play_no')->where('po.order_status in (3,6,-9) and po.is_pay=0 and po.create_dt<"'.date('Y-m-d H:i:s',$threeday_before).'" and p.play_status=4')->group('po.play_no')->select();
            foreach ($order as $key => $value) {
                $orders = Db::name('play_order')->where(['play_no'=>$value['play_no'],'order_status'=>['in',[3,6,-9,-8,-7]]])->count();
                $update['stock'] = $value['num']-$orders;
                $update['update_dt'] = date('Y-m-d H:i:s',$time);
                $update['update_by'] = 'crontab7';
                $update['play_status'] = 3;
                $update['acture_total_money'] = (float)\app\common\model\Order::where(['play_no'=>$value['play_no'],'order_status'=>['in',[3,6,-9]]])->value('sum(actual_rebate_amt+service_charge_amt)');
                Db::name('play')->where(['play_no'=>$value['play_no']])->update($update);
            }

            $play = Db::name('play')->where(['play_status'=>3,'pay_status'=>['in',[1,0]],'create_dt'=>['<',date('Y-m-d H:i:s',$threeday_before)]])->field('id,play_no')->order('id DESC')->select();
            $playidarr = [];
            foreach ($play as $key => $value) {
                $play_order = Db::name('play_order')->where(['play_no'=>$value['play_no'],'order_status'=>['in',[3,6,-9,-8,-7]],'is_pay'=>0])->count();
                if (!$play_order) {
                    $playidarr[] = $value['id'];
                }
            }
            Db::name('play')->where(['id'=>['in',$playidarr]])->update(['play_status'=>5,'pay_status'=>2,'update_by'=>'crontab8','last_pay_time'=>1]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }



    public function chooseOrder()
    {
        $order = Db::name('play_order')->where(['update_dt'=>['>','2023-11-23 19:50:00']])->select();
        foreach ($order as $key => $value) {
            $proof = Db::name('play_order_proof')->where(['play_order_no'=>$value['play_order_no']])->find();
            $play = Db::name('play')->where(['play_no'=>$value['play_no']])->find();
            $OcrService = new \app\api\service\OcrService();
            $res = $OcrService->ocr($play, $value, $proof ,$proof);
            var_dump($value['play_order_no'],$res['res']);
            echo '</br>';
        }

    }


    // 店铺昨日是否在线
    public function zrzx()
    {
        $start_time = strtotime(date('Y-m-d'))-86400;
        $end_time = strtotime(date('Y-m-d'));
        Db::startTrans();
        try {
            Db::name('shop')->where(['zrzx'=>1])->update(['zrzx'=>0]);
            $zrzx = Db::name('play')->where('super_play_no=0 and start_date >= '.$start_time.' and start_date<'.$end_time)->field('shop_no')->group('shop_no')->select();
            foreach ($zrzx as $key => $value) {
                Db::name('shop')->where(['shop_no'=>$value['shop_no']])->update(['zrzx'=>1]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }


    public function platform_no()
    {
        $sql = 'SELECT s.shop_no,s.shop_name,sp.platform_no FROM `chbc_shop` s left join chbc_shop_platform sp on sp.shop_no=s.shop_no WHERE s.`shop_status` = 1 AND s.`shop_type` = 3 and sp.platform_no!=""';
        $shop = Db::query($sql);
        foreach ($shop as $key => $value) {
            parse_str($value['platform_no'],$output);
            $appId = '';
            $storeId = '';
            $venderId = '';
            if (isset($output['appId'])) $appId = $output['appId'];
            if (isset($output['storeId'])) $storeId = $output['storeId'];
            if (isset($output['venderId'])) $venderId = $output['venderId'];
            $appId = 'B594E1702946F919D4B3B9C0DA5B4985';
            $platform_no = '?bizType=1&venderId='.$venderId.'&storeId='.$storeId.'&appId='.$appId;
            Db::name('shop_platform')->where('shop_no',$value['shop_no'])->update(['platform_no'=>$platform_no]);
        }
    }

}
